<?php

namespace Service;

use think\Db;
use Core\Di;
use Core\Exception;
use Helper\NetworkHelper;
use Extend\Alidayu\Alidayu;

/**
 * 阿里大于短信服务
 *
 * Class YarService
 * @package Service
 */
class AlidayuService
{
    protected static $config = [];

    /**
     * 获取参数
     * @throws
     */
    public static function setConfig()
    {
        if( empty(self::$config) ){
            self::$config = Db::name('sms')->find();
        }
        return true;
    }

    /**
     * @param $mobile
     * @param $action
     * @param array $tplvalue
     * @param int $type
     * @param int $userid
     * @return  bool
     * @throws
     */
    public static function send($mobile, $action, $tplvalue = [], $type= 0, $userid=0)
    {

        $smsTpl = Db::name('sms_templates')
            ->where(['action' => $action, 'type' => $type])
            ->find();
        if(empty($smsTpl)){
            throw new Exception(10110, '短信发送失败', [],'错误的Action');
        }
        if($smsTpl['require_login'] AND empty($userid) ){
            throw new Exception(10110, '短信发送失败', [],'短信类型需要登录');
        }
        if (DEBUG) {
            $smsResult = ['Code' => 'OK', 'Message' => '成功'];
        } else {
            self::setConfig();
            $smsResult = (new Sms(['templateCode'=>$smsTpl['tplid']]))->send_verify($mobile,$tplvalue);
        }
        $smsLog = [
            'action' => $action,
            'userid' => $userid??0,
            'mobile' => $mobile,
            'content' => implode(',', $tplvalue),
            'ip' => NetworkHelper::getClientIP(),
            'addtime' => time()
        ];
        if ($smsResult['Code'] == 'OK') {
            // 发送成功
            $smsLog['result'] = $smsResult['Message'];
            $smsLog['status'] = 1;
            Db::name('sms_log')->insert($smsLog);
            return true;
        }else{
            // 发送失败
            $smsLog['result'] = $smsResult['Message'] ;
            $smsLog['status'] = 0;
            Db::name('sms_log')->insert($smsLog);
            throw new Exception(10110, '短信发送失败', [],$smsResult['Message']);
        }
        return false;
    }

}